package com.example.service;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 审批任务监听器
 * 用于监听审批任务完成事件，实现或签逻辑
 */
@Component
public class ApprovalTaskListener implements FlowableEventListener {
    
    @Autowired
    private RuntimeService runtimeService;
    
    @Override
    public void onEvent(FlowableEvent event) {
        if (event instanceof FlowableEngineEvent) {
            FlowableEngineEvent engineEvent = (FlowableEngineEvent) event;
            
            // 当任务完成时触发
            if ("TASK_COMPLETED".equals(event.getType().name())) {
                TaskEntity taskEntity = (TaskEntity) engineEvent.getEntity();
                
                // 检查是否是审批任务
                if (taskEntity != null && "document-approval".equals(taskEntity.getCategory())) {
                    // 获取流程实例变量
                    String processInstanceId = taskEntity.getProcessInstanceId();
                    
                    // 获取审批结果
                    Boolean approved = (Boolean) runtimeService.getVariable(processInstanceId, "approved");
                    
                    // 如果审批通过，则触发信号，结束其他并行任务
                    if (approved != null && approved) {
                        runtimeService.signalEventReceived("approvalSignal", processInstanceId);
                    }
                }
            }
        }
    }
    
    @Override
    public boolean isFailOnException() {
        return false;
    }
    
    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }
    
    @Override
    public String getOnTransaction() {
        return null;
    }
}